package com.jule.teenpatti.mail.service;

import com.alibaba.fastjson.JSONObject;
import com.jule.core.jedis.JedisPoolWrap;
import com.jule.teenpatti.base.enums.RedisChannel;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisPubSub;

@Slf4j
public class MailSub extends Thread {

    @Override
    public void run() {
        final JedisPubSub jedisPubSub = new JedisPubSub() {
            public void onMessage(String channel, String message) {
                try {
                    log.info(String.format("receive redis published message, channel %s, message %s", channel, message));
                    //新邮件配置
                    if (channel.equals(RedisChannel.MAIL_NEW_CONFIG.getChannelName())) {
                        JSONObject jsonObject = JSONObject.parseObject(message);
                        String mailId = jsonObject.containsKey("mailConfigId") ? jsonObject.get("mailConfigId").toString() : "";
                        String type = jsonObject.containsKey("type") ? jsonObject.get("type").toString() : "";
                        MailConfigService.getInstance().loadNewConfig(Integer.parseInt(mailId),Integer.parseInt(type));
                    }


                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }

            }

            public void onSubscribe(String channel, int subscribedChannels) {
                log.info(String.format("subscribe redis channel success, channel %s, subscribedChannels %d",
                        channel, subscribedChannels));
            }

            public void onUnsubscribe(String channel, int subscribedChannels) {
                log.info(String.format("unsubscribe redis channel, channel %s, subscribedChannels %d",
                        channel, subscribedChannels));

            }
        };

        //订阅渠道消息
        JedisPoolWrap.getInstance().subscribe(
                jedisPubSub,
                RedisChannel.MAIL_NEW_CONFIG.getChannelName()
        );
    }
}
